package com.mini.framework.communicate.mina.adapter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.mini.framework.communicate.mina.Sender;
import com.mini.framework.communicate.mina.handler.HandlerFactory;
import com.mini.framework.communicate.mina.handler.MsgHandlerThread;
import com.mini.framework.communicate.mina.handler.SenderAdapter;
import com.mini.framework.communicate.mina.protocol.Msg;

public class MsgHandlerAdapter extends IoHandlerAdapter {
	
	private static final int DefaultPoolSize = 10;
	
	private HandlerFactory handlerFactory;
	
	private ExecutorService executor;
	
	public MsgHandlerAdapter(HandlerFactory handlerFactory){
		this(handlerFactory,DefaultPoolSize);
	}
	
	public MsgHandlerAdapter(HandlerFactory handlerFactory,int poolSize){
		executor = Executors.newFixedThreadPool(poolSize);
		this.handlerFactory = handlerFactory;
	}
	
	
	/**
	 * 
	 * 消息接收.
	 * 
	 */
	public void messageReceived(IoSession session,Object message) throws Exception{
		System.out.println("msg array...");
		Msg msg = (Msg) message;
		Sender sender = new SenderAdapter(session);
		msg.setSender(sender);
		MsgHandlerThread handlerThread = new MsgHandlerThread(handlerFactory,msg);
		executor.execute(handlerThread);
	}
	
	/**
	 * 异常接收.
	 */
	public void exceptionCaught(IoSession session,Throwable cause){
		System.out.println(cause.getMessage());
	}
	
	

}
